package cn.initcap.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty并非是MVC模型，没有明确区分各个层
 *
 * @author initcap
 * @date Created in 5/4/19 4:07 PM.
 */
public class WebSocketServer {

    public static void start(int port) throws Exception {
        // 这里采用主从线程模型，主线程用于接收连接请求，从线程用于处理业务逻辑
        EventLoopGroup mainGroup = new NioEventLoopGroup();
        EventLoopGroup subGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap server = new ServerBootstrap();
            server.group(mainGroup, subGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WebSocketServerInitialzer());

            ChannelFuture future = server.bind(port).sync();

            future.channel().closeFuture().sync();
        } finally {
            mainGroup.shutdownGracefully();
            subGroup.shutdownGracefully();
        }
    }

}
